//
//  MyViewController.m
//  Rabbit
//
//  Created by 阿帕 on 2018/11/3.
//  Copyright © 2018年 GCY. All rights reserved.
//

#import "MyViewController.h"

//customView
#import "MyHeadInfoView.h"
#import "MyAllBtnView.h"
#import "MyBottomView.h"

//controllers
#import "EditInfoViewController.h"
#import "SiJiManageViewController.h"
#import "CarTeamViewController.h"
#import "CarSourceViewController.h"
#import "InviteDriverJoinViewController.h"
#import "JoinedCheDuiViewController.h"
#import "TouSuListViewController.h"
#import "BankCardViewController.h"
#import "AccountInformationViewController.h"
#import "MyCommentsViewController.h"
#import "FeedbackViewController.h"
#import "AboutUsViewController.h"
#import "FreightStatisticsViewController.h"
#import "ElectronContractViewController.h"
#import "VehicleMaintenanceTabbar.h"
#import "PolicyViewController.h"
#import "VehicleListViewController.h"
#import "DriverAuthVC.h"
#import "CarTeamAuthVC.h"
#import "TaxAuthVC.h"
#import "CYWebViewViewController.h"
#import "TradeRecordsViewController.h"
#import "DriverVehicleListViewController.h"

#import "ScanViewController.h"
#import "LBXScanViewStyle.h"

#import "UIImage+CYCircle.h"

#import <AMapTrackKit/AMapTrackKit.h>

//人脸识别
#import "BDFaceLivenessViewController.h"
#import "BDFaceDetectionViewController.h"
#import "BDFaceLivingConfigModel.h"
#import "IDLFaceSDK/IDLFaceSDK.h"
#import "FaceParameterConfig.h"
#import "MyAccountViewController.h"
#import "ZTXInforQiYeViewController.h"
#import "IDentityCodeController.h"
#import "UpIDCodeController.h"
#import "IDCardAuthenticationController.h"
#import "DriverAuthenticationController.h"
//#import <>
@interface MyViewController () <MyCenterHeadInfoClickDelegate, MyCenterBtnClickDelegate, MyCenterBottomViewClickDelegate, AMapTrackManagerDelegate, AMapLocationManagerDelegate, UINavigationControllerDelegate>

@property(strong, nonatomic)UIScrollView *scrollView;

@property(strong, nonatomic)MyHeadInfoView *myHeadInfoView;

@property(strong, nonatomic)MyAllBtnView *myAllBtnView;

@property(strong, nonatomic)MyBottomView *myBottomView;

@property(nonatomic, strong)NSDictionary *infoDic;

@property (nonatomic, strong)AMapTrackManager *trackManager;

@property (nonatomic, strong)AMapLocationManager *locationManager;

@property (nonatomic, strong) NSString *isFirstRequest;//判断是否是第一次请求

//@property (nonatomic, strong)CLLocationManager *locationManager;

///猎鹰终端id
@property(nonatomic, copy)NSString *termiID;

@property(nonatomic, copy)NSString *netBankPaymentStr;

@property(nonatomic, copy)NSString *authMsgStr;//审核失败信息

@property(nonatomic, strong)NSString *licenseNumber;

@property(nonatomic, strong)NSString *driverautonymType;//司机实名认证状态
@property(nonatomic, strong)NSString *driverAuththenTicationType;//司机信息认证状态
@property(nonatomic, assign)BOOL driverTimebool;//司机证件到期

@end

@implementation MyViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (TOKEN_ISEMPTY) {
        
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            for (int i = 1; i<=3; i++) {
                [UIView animateWithDuration:0.5f animations:^{
                    UIView *view = [self.tabBarController.view viewWithTag:CJAlertDueTag+i];
                    view.alpha = 1;
                } completion:nil];
            }
        });
        [self personalCenterRequest];
        self.isFirstRequest = @"1";
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (int i = 1; i<=3; i++) {
        UIView *view = [self.tabBarController.view viewWithTag:CJAlertDueTag+i];
        view.alpha = 0;
    }
}

- (void)outdatedInfoValid {
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_INFO) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"认证信息获取" success:^(id response, NSString *msg) {
        
        // 司机端partyCode
        [UserDefaultUtil saveValue:response[@"partyCode"] forKey:DriverPartyCode];
        [UserDefaultUtil saveValue:response[@"code"] forKey:userDriverCode];
        self.authMsgStr = response[@"authMsg"];
        self.driverAuththenTicationType = response[@"authStatus"];

        // 过期信息验证
        if ([response[@"authStatus"] integerValue] < 3 || [DCSpeedy isBlankArr:response[@"overDueType"]] == NO) {
            [KNotificationCenter postNotificationName:@"AuthOverdue" object:@"0"];
            self.driverTimebool = NO;
        } else {
            [KNotificationCenter postNotificationName:@"AuthOverdue" object:@"1"];
            self.driverTimebool = YES;
        }
        
        // 需要获取到车队道路运输经营许可证，本地存储
        if (Identity_CarCaptain) {
            if ([DCSpeedy isBlankString:CJStringWithFormat(@"%@",response[@"roadPermitNumber"])] == NO && response[@"roadPermitNumber"] != NULL) {
                [UserDefaultUtil saveValue:response[@"roadPermitNumber"] forKey:ROADPERMITNUMBER];
            } else {
                [UserDefaultUtil saveValue:@"" forKey:ROADPERMITNUMBER];
            }
            if ([DCSpeedy isBlankString:CJStringWithFormat(@"%@",response[@"roadPermitNumberImg"])] == NO && response[@"roadPermitNumberImg"] != NULL) {
                [UserDefaultUtil saveValue:response[@"roadPermitNumberImg"] forKey:ROADPERMITNUMBERIMG];
            } else {
                [UserDefaultUtil saveValue:@"" forKey:ROADPERMITNUMBERIMG];
            }
        }
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationController.delegate = self;
    
    [KNotificationCenter addObserver:self selector:@selector(refreshDataEvent) name:LOGIN_SUCCESS object:nil];
    [KNotificationCenter addObserver:self selector:@selector(logoutEvent:) name:LOGIN_LOGOUT object:nil];
    //    [KNotificationCenter addObserver:self selector:@selector(faceIdentifyCompleted:) name:@"faceIdentifySuccess" object:nil];
    
    self.navigationItem.title = @"我的";
    
    self.scrollView.backgroundColor = RGB(249, 249, 249);
    
    [self setupBaseView];
    
}

- (void)dealloc {
    
    [KNotificationCenter removeObserver:self name:LOGIN_SUCCESS object:nil];
    [KNotificationCenter removeObserver:self name:LOGIN_LOGOUT object:nil];
    //    [KNotificationCenter removeObserver:self name:@"faceIdentifySuccess" object:nil];
}

- (void)refreshDataEvent {
    
    [self personalCenterRequest];
}

- (void)personalCenterRequest {
    
    WEAKSELF
    
    static BOOL appIsFirstLoad = YES;
    
    if (TOKEN_ISEMPTY) {
        
        _myHeadInfoView.userInfoDic = @{};
        
        [self.scrollView.mj_header endRefreshing];
        
    } else {
        
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN],@"version":@(1)} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
            if (Identity_CarCaptain == NO) { // SPT缓存车牌号、司机姓名
                
                NSString *plate = @"";
                NSString *name = @"";
                if (![DCSpeedy isBlankString:response[@"vehicleLicense"]]) {
                    plate = response[@"vehicleLicense"];
                }
                if (![DCSpeedy isBlankString:response[@"name"]]) {
                    name = response[@"name"];
                }
                [UserDefaultUtil saveValue:plate forKey:SPT_PLATE];
                [UserDefaultUtil saveValue:name forKey:SPT_NAME];
            }
            
            [UserDefaultUtil saveValue:response forKey:Login_Branch];
            [UserDefaultUtil saveValue:response[@"branchCode"] forKey:BranchCode];
            
            weakSelf.myHeadInfoView.userInfoDic = response;
            
            self.myAllBtnView.valueArray = @[CJStringWithFormat(@"%@",response[@"totalBalance"]), CJStringWithFormat(@"%@",response[@"bankCardNum"])];
            
            //            weakSelf.myBottomView.taxPlatform = [response[@"taxPlatform"] integerValue];
            // status==3通过 对号 2驳回  驳回 叉号》过期》xx
            NSInteger authStatus = [response[@"authStatus"] integerValue];
            weakSelf.myBottomView.authStatus = authStatus;
            if ([response[@"teamDriverCertificateHasDue"] integerValue] == 1) {
                // 车队司机证件到期
                weakSelf.myBottomView.driverCertificateHasDue = 1;
            } else {
                weakSelf.myBottomView.driverCertificateHasDue = 0;
            }
            
            if ([response[@"teamVehicleCertificateHasDue"] integerValue] == 1) {
                // 车队车辆证件到期
                weakSelf.myBottomView.vehicleCertificateHasDue = 1;
            } else {
                weakSelf.myBottomView.vehicleCertificateHasDue = 0;
            }
            
            [weakSelf outdatedInfoValid];
            
            [weakSelf checkIsHaveNetBankModule];
            
            weakSelf.infoDic = response;
            
            if ([response[@"merchSign"] integerValue] == 0 && ([response[@"merchSignType"] integerValue] == 0 || [response[@"merchSignType"] integerValue] == 1)) {
     
            } else {
                weakSelf.myBottomView.merchSign = [response[@"merchSign"] integerValue];
            }
            
            if (appIsFirstLoad) {
                //第一次加载时调用
                [self configLocationManager];
                
                [self startTrackAcquisition];
                
                appIsFirstLoad = NO;
            }
            self.driverautonymType = response[@"isRealNameAuthentication"];
            if ([response[@"isRealNameAuthentication"] intValue] == 0) {//司机实名认证状态
                [KNotificationCenter postNotificationName:@"AuthOverdueAutonym" object:@"0"];
            }else{
                [KNotificationCenter postNotificationName:@"AuthOverdueAutonym" object:@"1"];
            }
            if ([self.isFirstRequest isEqualToString:@"1"]) {
                self.isFirstRequest = @"2";
                if ([response[@"isRealNameAuthentication"] intValue] == 0) {//须实名认证 1 已认证 0未认证
                    if ([response[@"isOldParty"] intValue] == 0) {//是否是老用户 1老用户 0新用户
                        IDCardAuthenticationController * vc = [[IDCardAuthenticationController alloc] init];
                        [self.navigationController pushViewController:vc animated:YES];
                    }else{
                        IDentityCodeController *vc = [[IDentityCodeController alloc] init];
                        vc.name = response[@"name"];
                        vc.IDCod = response[@"idNo"];
                        vc.idCardDueDate = response[@"idCardDueDate"];
                        vc.isOldType = @"1";
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
            }
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
        
//        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/driver/driverOrderStatus") withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"获取二维码信息" success:^(id response, NSString *msg) {
//
//            NSArray *licenseNumbers = [response objectForKey:@"licenseNumbers"];
//            NSArray *mainOrderNumbers = [response objectForKey:@"mainOrderNumbers"];
//
//            if (mainOrderNumbers.count > 0) {
//                weakSelf.myHeadInfoView.qrCode = [[mainOrderNumbers firstObject] objectForKey:@"orderCodeOrCode"];
//            } else {
//                weakSelf.myHeadInfoView.qrCode = [[licenseNumbers firstObject] objectForKey:@"licenseNumberOrCode"];
//                weakSelf.licenseNumber = [[licenseNumbers firstObject] objectForKey:@"licenseNumber"];
//            }
//
//        } failure:^(NSInteger code, NSString *msg) {
//
//        }];
    }
    
}

#pragma mark - 发起高德猎鹰轨迹上传
- (void)openGaoDeTrackSDK {
    
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = _infoDic[@"amapSid"];
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    //配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
    
    //将定位信息采集周期设置为2，上报周期设置为20s(这个根据实际需要自行设置)
    [self.trackManager changeGatherAndPackTimeInterval:2 packTimeInterval:20];
    
    //配置本地缓存大小 猎鹰sdk会在无法正常上报轨迹点时将未成功上报的轨迹点缓存在本地，默认最多缓存50MB数据。
    [self.trackManager setLocalCacheMaxSize:20];
    
    AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
    serviceOption.terminalID = _infoDic[@"amapTid"];
    [self.trackManager startServiceWithOptions:serviceOption];
}

- (void)setupBaseView {
    
    //头像区域
    _myHeadInfoView = [[MyHeadInfoView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 100 + NavHeight)];
    _myHeadInfoView.delegate = self;
    [self.view addSubview:_myHeadInfoView];
    
    //九宫格部分
    _myAllBtnView = [[MyAllBtnView alloc] initWithFrame:CGRectMake(0, _myHeadInfoView.cy_bottom, ScreenW, 70)];
    _myAllBtnView.delegate = self;
    [self.view addSubview:_myAllBtnView];
    
    //联系我们部分
    _myBottomView = [[MyBottomView alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 14*45 + 85  + 80 + 40)];
    _myBottomView.delegate = self;
    [_scrollView addSubview:_myBottomView];
    
    _scrollView.contentSize = CGSizeMake(ScreenW, 14*45 + 10 + 85 + 40);
}

#pragma mark - 校验是否有网商银行模块
- (void)checkIsHaveNetBankModule {
    /*
     "payment_type" : {
     "configDesc" : "系统选择的支付方式，arpa:中台集中支付，mybank:网商银行，arpa_2:云企付;",
     "configValue" : "mybank",
     "configKey" : "type",
     "type" : "payment"
     }
     */
    if ([UserDefaultUtil valueForKey:Login_Branch] != NULL) {
        NSDictionary *userInfo = [UserDefaultUtil valueForKey:Login_Branch];
        _netBankPaymentStr = [userInfo valueForKey:@"paymentType"];
        if ([_netBankPaymentStr isEqual:@"arpa"]) {
            // 无网商功能或云企付
            _myAllBtnView.hidden = YES;
            _scrollView.frame = CGRectMake(0, 110 + NavHeight, ScreenW, ScreenH - NavHeight - TabBarHeight - 110);
        }
    }
}

#pragma mark - MyCenterHeadInfoClickDelegate
- (void)MyHeadInfoBtnClick:(NSInteger)index {
    
    if (index == 10) {
        //编辑信息
        if ([DCSpeedy judgeUserIsLogin] == NO) return;
        
        EditInfoViewController *eivc = [[EditInfoViewController alloc] init];
        eivc.infoDic = _infoDic;
        [self.navigationController pushViewController:eivc animated:YES];
        
    }else if (index == 11) {
        //登录注册
        [DCSpeedy judgeUserIsLogin];
    }
    
}

#pragma mark - MyCenterBtnClickDelegate
- (void)getButtonIndex:(NSInteger)index {
    
    if ([DCSpeedy judgeUserIsLogin] == NO) return;
    
    switch (index) {
        case 100:
            //账户信息
        {
            MyAccountViewController *aivc = [[MyAccountViewController alloc] init];
//            AccountInformationViewController *aivc = [[AccountInformationViewController alloc] init];
            [self.navigationController pushViewController:aivc animated:YES];
        }
            break;
        case 101:
            //银行卡
        {
            BankCardViewController *bcvc = [[BankCardViewController alloc] init];
            [self.navigationController pushViewController:bcvc animated:YES];
//            IDCardAuthenticationController *bcvc = [[IDCardAuthenticationController alloc] init];
//            [self.navigationController pushViewController:bcvc animated:YES];

        }
            break;
    }
}

#pragma mark - MyCenterBottomViewClickDelegate
- (void)CalculateMenuListHeight:(NSInteger)height {
    
    _myBottomView.cy_height = height + 85 + 40;
    _scrollView.contentSize = CGSizeMake(ScreenW, 20 + height + 85 + 40);
    
    //    if ([DCSpeedy isBlankString:[UserDefaultUtil valueForKey:Login_Branch][@"merchSign"]] == NO) {
    //        if (Identity_Driver && ([[UserDefaultUtil valueForKey:Login_Branch][@"merchSign"] integerValue] == 0)) {
    //            _myBottomView.height = height + 125;
    //            _scrollView.contentSize = CGSizeMake(ScreenW, 20 + height + 125);
    //        }
    //    }
}

- (void)MyBottomViewBtnClick:(NSInteger)index andBtnTitle:(NSString *)title {
    //下面操作菜单
    if (![title isEqual:@"关于我们"]) {
        if ([DCSpeedy judgeUserIsLogin] == NO) return;
    }
    
    if ([title isEqual:@"实名认证"]) {
        if ([self.driverautonymType intValue] == 1 ) {
            [XSInfoView showInfo:@"实名认证已成功" onView:self.view];
        }else{
            IDCardAuthenticationController * VC = [[IDCardAuthenticationController alloc] init];
            [self.navigationController pushViewController:VC animated:YES];
        }
    }else if ([title isEqual:@"司机认证信息"] || [title isEqual:@"认证信息"]) {
        /**
         authStatus
         0未审核/1审核中/2审核未通过/3审核通过
         */
/*        if ([self.driverAuththenTicationType intValue] == 3 && [self.driverAuththenTicationType intValue] == 1 && !self.driverTimebool == NO) { */       if ([self.driverAuththenTicationType intValue] == 0 || [self.driverAuththenTicationType intValue] == 2) {
    if ([[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue] == 0) {
        DriverAuthenticationController *vc = [[DriverAuthenticationController alloc] init];
        if (self.authMsgStr.length > 0) {
            vc.authMsgStr = self.authMsgStr;
        }
        [self.navigationController pushViewController:vc animated:YES];
//            DriverAuthVC *davc = [[DriverAuthVC alloc] init];
//            [self.navigationController pushViewController:davc animated:YES];
        
    } else {

        DriverAuthVC *davc = [[DriverAuthVC alloc] init];
        davc.isNotEdit = YES;
        [self.navigationController pushViewController:davc animated:YES];
    }
           
        }else{
            [XSInfoView showInfo:@"司机信息认证已成功/审核中不允许修改" onView:self.view];
        }
       
        
    } else if ([title isEqual:@"车队认证信息"]) {
        
        CarTeamAuthVC *ctavc = [[CarTeamAuthVC alloc] init];
        [self.navigationController pushViewController:ctavc animated:YES];
        
    } else if ([title isEqual:@"司机管理"]) {
        
        SiJiManageViewController *sjmvc = [[SiJiManageViewController alloc] init];
        [self.navigationController pushViewController:sjmvc animated:YES];
        
    } else if ([title isEqual:@"司机加入"]) {
        
        InviteDriverJoinViewController *idjvc = [[InviteDriverJoinViewController alloc] init];
        [self.navigationController pushViewController:idjvc animated:YES];
        
    } else if ([title isEqual:@"加入车队"]) {
        //加入车队
        CarTeamViewController *ctvc = [[CarTeamViewController alloc] init];
        [self.navigationController pushViewController:ctvc animated:YES];
        
    }else if ([title isEqual:@"已加入车队列表"]) {
        
        JoinedCheDuiViewController *jcdvc = [[JoinedCheDuiViewController alloc] init];
        [self.navigationController pushViewController:jcdvc animated:YES];
        
    }else if ([title isEqual:@"车辆管理"]) {
        
        NSInteger driverType = [[UserDefaultUtil valueForKey:DRIVER_TYPE] integerValue];
        if (driverType == 0) {
            //0独立司机
            DriverVehicleListViewController *vc = [DriverVehicleListViewController new];
            
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            VehicleListViewController *vlvc = [[VehicleListViewController alloc] init];
            vlvc.isCanBindVehicle = 0;
            [self.navigationController pushViewController:vlvc animated:YES];
        }
        
    }else if ([title isEqualToString:@"投诉记录"]) {
        
        TouSuListViewController *tslvc = [[TouSuListViewController alloc] init];
        tslvc.pagesFlag = 1;
        tslvc.isShowSegmentedControl = YES;
        [self.navigationController pushViewController:tslvc animated:YES];
        
    }else if ([title isEqualToString:@"电子合同"]) {
        
        ElectronContractViewController *ecvc = [[ElectronContractViewController alloc] init];
        [self.navigationController pushViewController:ecvc animated:YES];
        
    } else if ([title isEqualToString:@"付款记录"]) {
        
    } else if ([title isEqualToString:@"运费统计"]) {
        
        FreightStatisticsViewController *fsvc = [[FreightStatisticsViewController alloc] init];
        [self.navigationController pushViewController:fsvc animated:YES];
        
    }else if ([title isEqualToString:@"车辆年检业务"]) {
        
        ZTXInforQiYeViewController *fsvc = [[ZTXInforQiYeViewController alloc] init];
        [self.navigationController pushViewController:fsvc animated:YES];
        
    } else if ([title isEqualToString:@"用户评价"]) {
        
        MyCommentsViewController *mcvc = [[MyCommentsViewController alloc] init];
        [self.navigationController pushViewController:mcvc animated:YES];
        
    } else if ([title isEqualToString:@"投诉意见反馈"]) {
        
        FeedbackViewController *fvc = [[FeedbackViewController alloc] init];
        [self.navigationController pushViewController:fvc animated:YES];
        
    } else if ([title isEqualToString:@"关于我们"]) {
       
        AboutUsViewController *auvc = [[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:auvc animated:YES];
        
    } else if ([title isEqualToString:@"车辆维修"]) {
        
        VehicleMaintenanceTabbar *vmtVC = [[VehicleMaintenanceTabbar alloc] init];
        [self.navigationController pushViewController:vmtVC animated:YES];
        
    } else if ([title isEqualToString:@"我的车源信息"]) {
        
        CarSourceViewController *csvc = [[CarSourceViewController alloc] init];
        [self.navigationController pushViewController:csvc animated:YES];
        
    } else if ([title isEqualToString:@"保单列表"]) {
        
        PolicyViewController *pvc = [[PolicyViewController alloc] init];
        [self.navigationController pushViewController:pvc animated:YES];
        
    } else if ([title isEqualToString:@"免验授权"]) {
        
        //        merchSign：授权状态，0待授权（默认），1授权中，2已授权，3授权失败
        //        merchSignT ype  0未进行过授权 1线上授权 2线下授权
        
        if (_infoDic[@"merchSign"] != NULL) {
            
            if ([_infoDic[@"merchSign"] integerValue] == 0 && ([_infoDic[@"merchSignType"] integerValue] == 0 || [_infoDic[@"merchSignType"] integerValue] == 1)) {
                
                NSDictionary *parmas = @{
                    @"sysType": @"app",
                    @"appType": @"driver",
                    @"branchCode": [UserDefaultUtil valueForKey:BranchCode],
                    @"page": @"main",
                    @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
                };
                
                [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], MERCHPREAPPLY) withParameter:parmas withVC:self netName:@"免验授权" success:^(id response, NSString *msg) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:response]];
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
                
            } else if ([_infoDic[@"merchSign"] integerValue] == 1) {
                [XSInfoView showInfo:@"授权中" onView:self.view];
            } else if ([_infoDic[@"merchSign"] integerValue] == 2) {
                [XSInfoView showInfo:@"已授权" onView:self.view];
            } else if ([_infoDic[@"merchSign"] integerValue] == 3) {
                [XSInfoView showInfo:@"授权失败" onView:self.view];
            } else if ([_infoDic[@"merchSignType"] integerValue] == 2) {
                [XSInfoView showInfo:@"线下授权" onView:self.view];
            }
        }
    } else if ([title isEqualToString:@"扫码绑车"]) {
        
        //设置扫码区域参数
        LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
        //扫码框中心位置与View中心位置上移偏移像素(一般扫码框在视图中心位置上方一点)
        style.centerUpOffset = 44;
        //扫码框周围4个角的类型设置为在框的上面,可自行修改查看效果
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_On;
        //扫码框周围4个角绘制线段宽度
        style.photoframeLineW = 6;
        //扫码框周围4个角水平长度
        style.photoframeAngleW = 24;
        //扫码框周围4个角垂直高度
        style.photoframeAngleH = 24;
        //动画类型：网格形式，模仿支付宝
        style.anmiationStyle = LBXScanViewAnimationStyle_NetGrid;
        //动画图片:网格图片
        style.animationImage = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_part_net"];;
        //扫码框周围4个角的颜色
        style.colorAngle = [UIColor colorWithRed:65./255. green:174./255. blue:57./255. alpha:1.0];
        //是否显示扫码框
        style.isNeedShowRetangle = YES;
        //扫码框颜色
        style.colorRetangleLine = [UIColor colorWithRed:247/255. green:202./255. blue:15./255. alpha:1.0];
        //非扫码框区域颜色(扫码框周围颜色，一般颜色略暗)
        //必须通过[UIColor colorWithRed: green: blue: alpha:]来创建，内部需要解析成RGBA
        style.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        ScanViewController *vc = [[ScanViewController alloc] init];
        vc.libraryType = SLT_Native;
        vc.style = style;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if ([title isEqualToString:@"税务认证"]) {
        
        TaxAuthVC *tavc = [[TaxAuthVC alloc] init];
        [self.navigationController pushViewController:tavc animated:YES];
        
        //        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
        //
        //            if ([response[@"isRealPeople"] intValue] == 1) {
        //                //已进行了人脸核验
        //                [XSInfoView showInfo:@"人证核验已通过" onView:self.view];
        //            } else {
        //                //未进行人脸核验
        //                if ([response[@"authStatus"] intValue] == 3) {
        //                    //平台认证已通过，去认证人脸
        //                    if (![[FaceSDKManager sharedInstance] canWork]) {
        //                        NSString* licensePath = [NSString stringWithFormat:@"%@.%@", FACE_LICENSE_NAME, FACE_LICENSE_SUFFIX ];
        //                        [[FaceSDKManager sharedInstance] setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath andRemoteAuthorize:YES];
        //                    }
        //                    [self faceLiveness];
        //
        //                } else {
        //                    [XSInfoView showInfo:@"您的信息未认证,请先认证信息" onView:self.view];
        //                }
        //            }
        //
        //        } failure:^(NSInteger code, NSString *msg) {
        //
        //        }];
        
    } else if ([title isEqualToString:@"交易记录"]) {
        
        TradeRecordsViewController *trvc = [[TradeRecordsViewController alloc] init];
        trvc.isOnlyBankRecord = YES;
        [self.navigationController pushViewController:trvc animated:YES];
        
    } else if ([title isEqualToString:@"银行卡信息"]) {
       
        BankCardViewController *bcvc = [[BankCardViewController alloc] init];
        [self.navigationController pushViewController:bcvc animated:YES];
        
    } else if ([title isEqualToString:@"提现协议签约"]) {
        
        [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@/ntocc-tms-api/arpaMerchant/mobileSignProtocol", [ReAddressDynamic shared].baseUrl) withParameter:nil withVC:self netName:@"提现协议签约" success:^(id response, NSString *msg) {
            
            if (response) {
                
                if ([response[@"isForward"] boolValue] == YES) {
                    CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
                    webVC.titleString = @"提现协议签约";
                    webVC.urlString = response[@"signUrl"];
                    webVC.state = 1;
                    [self.navigationController pushViewController:webVC animated:YES];
                    
                } else {
                    
                    [XSInfoView showInfo:msg onView:self.view];
                }
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }
}

//人脸认证
//- (void)faceLiveness {
//    BDFaceLivenessViewController* lvc = [[BDFaceLivenessViewController alloc] init];
//    BDFaceLivingConfigModel* model = [BDFaceLivingConfigModel sharedInstance];
//    [lvc livenesswithList:model.liveActionArray order:model.isByOrder numberOfLiveness:model.numOfLiveness];
//    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:lvc];
//    navi.navigationBarHidden = true;
//    navi.modalPresentationStyle = UIModalPresentationFullScreen;
//    [self presentViewController:navi animated:YES completion:nil];
//}

#pragma mark - 人证核验结果通知
//- (void)faceIdentifyCompleted:(NSNotification *)notifi {
//
//    NSDictionary *parmas = @{
//        @"peopleImg": notifi.object,
//    };
//    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/driver/driverRealPeopleCertification", BasicDomainURL) withParameter:parmas withVC:self netName:@"人证核验结果通知" success:^(id response, NSString *msg) {
//
//        [XSInfoView showInfo:msg onView:self.view];
//
//        [self personalCenterRequest];
//
//    } failure:^(NSInteger code, NSString *msg) {
//
//    }];
//}

- (void)startTrackAcquisition {
    
    [SystemPermissionsToolObject openLocationServiceWithBlock:^(BOOL isOpen) {
        if (isOpen) {
            /**
             amapSid 高德地图服务id
             amapTid 高德地图终端id
             amapTrid 高德地图轨迹id
             */
            
            //            [self createTerminalID];
            [self openGaoDeTrackSDK];
            
        } else {
            LineErrorInfo *errInfo = [LineErrorInfo new];
            [self appLineErrorInfo:errInfo errorCode:106];
            
            UIAlertController *alertView=[UIAlertController alertControllerWithTitle:@"温馨提示" message: CJStringWithFormat(@"请到设置->隐私->定位服务中开启【%@】定位服务，以便于获得您的当前地理位置信息", APP_NAME) preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"立即开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertView addAction:sureAction];
            [alertView addAction:cancelAction];
            
            [self presentViewController:alertView animated:YES completion:nil];
        }
        
    }];
    
}

#pragma mark - Actions
// 第一步：开始轨迹服务(开始前要先查询是否存在终端id，如果有直接使用，没有则创建)
-(void)startTrackServer{
    //开始服务
    AMapTrackManagerServiceOption *serviceOption = [[AMapTrackManagerServiceOption alloc] init];
    serviceOption.terminalID = self.termiID;
    
    [self.trackManager startServiceWithOptions:serviceOption];
}

/**
 第二步：创建终端ID
 : 创建之前要先查询终端id是否存在，查询和创建都要使用后台给的服务id(serviceID), 再根据终端名称(我这里用的是userid),来进行查询和创建，如果存在则不创建，直接通过终端id开启轨迹服务。
 2：如果查询后终端id不存在，则要进行创建，创建成功后再开启轨迹服务
 */
//创建终端ID
-(void)createTerminalID{
    /**
     amapSid 高德地图服务id
     amapTid 高德地图终端id
     amapTrid 高德地图轨迹id
     */
    //Service ID 根据需要进行修改
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    //    110618 110358 105618 105618
    option.serviceID = [NSString nullToString:CJStringWithFormat(@"%@", _infoDic[@"amapSid"])];
    DebugLog(@"amapSid = %@", [NSString nullToString:CJStringWithFormat(@"%@", _infoDic[@"amapSid"])]);
    //初始化AMapTrackManager
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    //配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
    
    //将定位信息采集周期设置为2，上报周期设置为20s(这个根据实际需要自行设置)
    [self.trackManager changeGatherAndPackTimeInterval:2 packTimeInterval:20];
    
    //配置本地缓存大小 猎鹰sdk会在无法正常上报轨迹点时将未成功上报的轨迹点缓存在本地，默认最多缓存50MB数据。
    [self.trackManager setLocalCacheMaxSize:20];
    
    //查询终端是否存在
    AMapTrackQueryTerminalRequest *request = [[AMapTrackQueryTerminalRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalName = APP_NAME; //根据userID创建终端id [UserDefaultUtil valueForKey:USER_TOKEN]
    [self.trackManager AMapTrackQueryTerminal:request];
}

//查询终端结果
- (void)onQueryTerminalDone:(AMapTrackQueryTerminalRequest *)request response:(AMapTrackQueryTerminalResponse *)response
{
    //查询成功
    if ([[response terminals] count] > 0) {
        //查询到结果，使用 Terminal ID
        NSString *terminalID = [[[response terminals] firstObject] tid];
        NSLog(@"terminalID == %@",terminalID);
        self.termiID = terminalID;
        
        //启动轨迹上报服务
        [self startTrackServer];
    }
    else {
        //查询结果为空，创建新的terminal
        AMapTrackAddTerminalRequest *addRequest = [[AMapTrackAddTerminalRequest alloc] init];
        addRequest.serviceID = self.trackManager.serviceID;
        addRequest.terminalName = APP_NAME; //根据userID创建终端id;
        [self.trackManager AMapTrackAddTerminal:addRequest];
    }
}

#pragma mark - AMapTrackManagerDelegate

- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    if ([request isKindOfClass:[AMapTrackAddTrackRequest class]]) {
        //        _trackIDSegment.enabled = YES;
    }
    
    NSLog(@"didFailWithError:%@; --- associatedRequest:%@;", error, request);
}

//创建终端结果
- (void)onAddTerminalDone:(AMapTrackAddTerminalRequest *)request response:(AMapTrackAddTerminalResponse *)response {
    //创建terminal成功
    NSString *terminalID = [response terminalID];
    NSLog(@"终端id == %@",terminalID);
    self.termiID = terminalID;
    
    //启动轨迹上报服务
    [self startTrackServer];
}

- (void)onStartService:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //开始服务成功
        NSLog(@"开始轨迹服务成功");
        //服务成功后，开始轨迹采集
        [self startTrackGather];
        
    } else {
        //开始服务失败
        NSLog(@"开始轨迹服务失败");
        NSLog(@"onStartService:%ld", (long)errorCode);
        
        LineErrorInfo *errInfo = [LineErrorInfo new];
        NSString *lonlat = [NSString stringWithFormat:@"%@,%@",[UserDefaultUtil valueForKey:LONGITUDE], [UserDefaultUtil valueForKey:LATITUDE]];
        errInfo.longitudeAndLatitude = lonlat;
        
        [self appLineErrorInfo:errInfo errorCode:errorCode];
    }
    
}

/**
 第三步：上报服务成功后，创建轨迹id (因为后台要根据轨迹id查询具体人员的轨迹，所以要创建轨迹id)
 */
//创建轨迹ID
- (void)doCreateTrackName {
    if (self.trackManager == nil) {
        return;
    }
    
    NSLog(@"创建轨迹ID");
    AMapTrackAddTrackRequest *request = [[AMapTrackAddTrackRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = self.trackManager.terminalID;
    
    [self.trackManager AMapTrackAddTrack:request];
}

//生成轨迹ID
- (void)onAddTrackDone:(AMapTrackAddTrackRequest *)request response:(AMapTrackAddTrackResponse *)response
{
    NSLog(@"onAddTrackDone%@", response.formattedDescription);
    
    if (response.code == AMapTrackErrorOK) {
        //创建trackID成功，开始采集
        self.trackManager.trackID = response.trackID;
        NSLog(@"轨迹ID == %@",response.trackID);
        
        //在巡检过程中杀死应用后，需要重启上报服务，但轨迹id被清空，不能继续开始轨迹采集，所以需要本地存储，巡检结束后删除
        //        [UserDefaultUtil setValue:forKey:@""];
        [UserDefaultUtil saveValue:response.trackID  forKey:@"trackID"];
        //开始采集轨迹
        [self.trackManager startGatherAndPack];
        
        //        if (self.isUplodTrack) {
        //            //上传轨迹
        //           //这里轨迹已经开始采集成功，请求后台接口上传相关的数据
        //        }
    }else {
        //创建trackID失败
        NSLog(@"创建trackID失败");
    }
}


/**
 第四步：生成轨迹id后，开始轨迹采集
 */
//开始轨迹采集
-(void)startTrackGather{
    
    if ([DCSpeedy isBlankString:_infoDic[@"amapTrid"]]) {
        //轨迹id不存在，创建轨迹id
        [self doCreateTrackName];
    }else{
        //轨迹id已存在，直接开始采集
        DebugLog(@"轨迹id已存在，直接开始采集 == %@", _infoDic[@"amapTrid"]);
        self.trackManager.trackID = _infoDic[@"amapTrid"];
        [self.trackManager startGatherAndPack];
        
        //        if (self.isUplodTrack) {
        //            //上传轨迹
        //           //这里轨迹已经开始采集成功，请求后台接口上传相关的数据
        //        }
    }
}

- (void)onStartGatherAndPack:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        //开始采集成功
        NSLog(@"开始轨迹采集成功");
    } else {
        //开始采集失败
        NSLog(@"开始轨迹采集失败");
        NSLog(@"onStartGatherAndPack:%ld", (long)errorCode);
        
        LineErrorInfo *errInfo = [LineErrorInfo new];
        NSString *lonlat = [NSString stringWithFormat:@"%@,%@",[UserDefaultUtil valueForKey:LONGITUDE], [UserDefaultUtil valueForKey:LATITUDE]];
        errInfo.longitudeAndLatitude = lonlat;
        
        [self appLineErrorInfo:errInfo errorCode:errorCode];
    }
}

//第五步：结束巡检后，关闭轨迹服务 （先关闭轨迹采集，再关闭服务）
-(void)stopTrackServer{
    //关闭轨迹采集
    [self.trackManager stopGaterAndPack];
    //关闭轨迹服务
    [self.trackManager stopService];
    self.trackManager.delegate = nil;
    self.trackManager = nil;
    //删除轨迹id
    [UserDefaultUtil removeForKey:@"trackID"];
}

- (void)onStopService:(AMapTrackErrorCode)errorCode {
    if (errorCode == AMapTrackErrorOK) {
        NSLog(@"成功关闭轨迹服务");
    }else{
        NSLog(@"关闭轨迹服务错误");
        LineErrorInfo *errInfo = [LineErrorInfo new];
        NSString *lonlat = [NSString stringWithFormat:@"%@,%@",[UserDefaultUtil valueForKey:LONGITUDE], [UserDefaultUtil valueForKey:LATITUDE]];
        errInfo.longitudeAndLatitude = lonlat;
        
        [self appLineErrorInfo:errInfo errorCode:errorCode];
    }
}

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    // 设置定位精度200米 200米去查询一次
    self.locationManager.distanceFilter = 50;
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置允许连续定位逆地理
    [self.locationManager setLocatingWithReGeocode:YES];
    
    [self.locationManager startUpdatingLocation];
}
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

#pragma mark - AMapLocationManager Delegate
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.longitude) forKey:LONGITUDE];
    [UserDefaultUtil saveValue:CJStringWithFormat(@"%f",location.coordinate.latitude) forKey:LATITUDE];
    
    LineErrorInfo *errInfo = [LineErrorInfo new];
    NSString *lonlat = [NSString stringWithFormat:@"%@,%@",CJStringWithFormat(@"%f",location.coordinate.longitude), CJStringWithFormat(@"%f",location.coordinate.latitude)];
    errInfo.longitudeAndLatitude = lonlat;
    
    WEAKSELF
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [weakSelf appLineErrorInfo:errInfo errorCode:AMapTrackErrorOK];
    });

}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    
    DebugLog(@"定位error：%@",error);
    LineErrorInfo *errInfo = [LineErrorInfo new];
    errInfo.remark = error.localizedDescription;
    
    NSString *lonlat = [NSString stringWithFormat:@"%@,%@",[UserDefaultUtil valueForKey:LONGITUDE], [UserDefaultUtil valueForKey:LATITUDE]];
    errInfo.longitudeAndLatitude = lonlat;
    
//    [self appLineErrorInfo:errInfo errorCode:error.code];
}

/// 上报线路定位错误
/// @param errInfo 错误信息
- (void)appLineErrorInfo:(LineErrorInfo *)errInfo errorCode:(AMapTrackErrorCode)errorCode {
    errInfo.driverCode = [UserDefaultUtil valueForKey:Login_Branch][@"code"];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *date = [formatter stringFromDate:[NSDate date]];
    errInfo.occurrenceTime = date;
    
    switch (errorCode) {
        case 10000:
            errInfo.remark = @"没有错误";
            break;
        case 100:
            errInfo.remark = @"未知错误";
            break;
        case 101:
            errInfo.remark = @"option包含错误参数";
            break;
        case 102:
            errInfo.remark = @"service已经启动";
            break;
        case 103:
            errInfo.remark = @"service已经停止";
            break;
        case 104:
            errInfo.remark = @"gather已经开始";
            break;
        case 105:
            errInfo.remark = @"gather已经停止";
            break;
        case 106:
            errInfo.remark = @"没有定位权限";
            break;
        case 107:
            errInfo.remark = @"获取定位失败";
            break;
        case 1800:
            errInfo.remark = @"服务返回数据为空";
            break;
        case 1801:
            errInfo.remark = @"协议解析错误，通常是返回结果无法解析";
            break;
        case 1802:
            errInfo.remark = @"连接超时";
            break;
        case 1803:
            errInfo.remark = @"URL异常";
            break;
        case 1804:
            errInfo.remark = @"找不到主机";
            break;
        case 1805:
            errInfo.remark = @"服务器连接失败";
            break;
        case 1806:
            errInfo.remark = @"连接异常，通常为没有网络的情况";
            break;
        case 1807:
            errInfo.remark = @"连接取消";
            break;
        case 2031:
            errInfo.remark = @"自定义参数获取异常";
            break;
            
        default:
//            errInfo.remark = [NSString stringWithFormat:@"错误码：%ld", (long)errorCode];
            break;
    }
    
    id param = [errInfo modelToJSONObject];
    [HTTPManager jsonNetworkRequestWithMethod:@"POST" urlString:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], AppLineErrorInfo) withParameter:param withVC:self netName:@"保存移动端app轨迹查询错误" success:^(id response, NSString *msg) {
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
}

///退出登录
- (void)logoutEvent:(NSNotification *)notification {
    
    [self stopTrackServer];
    
    [self cleanUpAction];
}

#pragma mark - lazyLoad
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 180 + NavHeight, ScreenW, ScreenH - NavHeight - TabBarHeight - 180)];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

@end
